package com.hgd.security.evp.biz.rest;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.hgd.security.evp.biz.biz.EvpUserBiz;
import com.hgd.security.evp.biz.config.HgdAuthorizePermitAntMatchersHandler;
import com.hgd.security.evp.biz.entity.EvpUser;
import com.hgd.security.evp.biz.interf.AuthorizePermitAntMatchersHandler;
import com.hgd.security.evp.biz.rabbitmq.HGDRabbitMQSender;
import com.hgd.security.evp.biz.vo.EvpUserVo;
import com.hgd.security.evp.biz.websocket.ChatHandler;
import com.hgd.security.evp.common.util.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author By 尚
 * @date 2019/3/28 23:44
 */
@RestController
public class TestController {

    @Autowired
    private AuthorizePermitAntMatchersHandler authorizePermitAntMatchersHandler;

    @Autowired
    private HgdAuthorizePermitAntMatchersHandler hgdAuthorizePermitAntMatchersHandler;

    @Autowired
    private ChatHandler chatHandler;

    @Autowired
    private Environment environment;

    @Autowired
    private EvpUserBiz evpUserBiz;

    @Autowired
    private HGDRabbitMQSender rabbitMQSender;


    private ReentrantLock lock=new ReentrantLock();

    @GetMapping("/test01")
    public JSONObject test01(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("name", "wangkaige");
        jsonObject.put("sex", "男");
        jsonObject.put("date", new Date());
        List<String> permitAntMatchers = authorizePermitAntMatchersHandler.getPermitAntMatchers();

        String msg="服务器主动向客户端推送的消息";
        try {
//            chatHandler.channelWriteAndFlush(msg);
//            chatHandler.channelWriteAndFlush(msg, "2551939f");
        } catch (Exception e) {
            e.printStackTrace();
        }

        int textInt = hgdAuthorizePermitAntMatchersHandler.getTextInt();
        jsonObject.put("textInt", textInt);
        hgdAuthorizePermitAntMatchersHandler.setTextInt(++textInt);

        DruidDataSource druidData = SpringContextUtil.getBeanByClassType(DruidDataSource.class);
//        System.out.println(druidData);

        Properties properties1 = System.getProperties();
        Properties properties = properties1;
        String property1 = System.getProperty("spring.application.name");
        String property = environment.getProperty("spring.application.name");
        String[] activeProfiles = environment.getActiveProfiles();
        String[] defaultProfiles = environment.getDefaultProfiles();

        jsonObject.put("defaultProfiles", defaultProfiles);
        jsonObject.put("activeProfiles", activeProfiles);

        reentrantLockParam();
//        synchronizedParam();

        return jsonObject;
    }

    private void synchronizedParam() {
        synchronized (this){

            EvpUser evpUser = evpUserBiz.selectById(1);
            System.out.println(Thread.currentThread().getId()+"::"+evpUser.getPhone());
            Integer integer = Integer.valueOf(evpUser.getPhone());
            evpUser.setPhone(String.valueOf(integer+1));

            evpUserBiz.updateById(evpUser);
        }
    }

    private void reentrantLockParam() {
        try {
            lock.lockInterruptibly();
            EvpUser evpUser = evpUserBiz.selectById(1);
            System.out.println(Thread.currentThread().getId()+"::"+evpUser.getPhone());
            Integer integer = Integer.valueOf(evpUser.getPhone());
            evpUser.setPhone(String.valueOf(integer+1));

            evpUserBiz.updateById(evpUser);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    @GetMapping("/static/test02")
    public JSONObject test02(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("name", "wangkaige");
        jsonObject.put("sex", "男");
        jsonObject.put("date", new Date());

        int textInt = hgdAuthorizePermitAntMatchersHandler.getTextInt();
        hgdAuthorizePermitAntMatchersHandler.setTextInt(0);
        jsonObject.put("textInt", 0);
        return jsonObject;
    }

    @GetMapping("/withTX")
    public JSONObject withTX(){
        JSONObject result=new JSONObject();

        long start=System.currentTimeMillis();
        for(int i=0;i<500;i++){
            EvpUser user=new EvpUserVo();
            user.setPhone(String.valueOf(i));
            user.setEvpAccount("wangkaige"+i);
//            user.setEvpPassword();
            user.setAddr("addr"+i);
            user.setDescription("desc"+i);
            user.setEmail("13821211755@163.com");
            user.setSex("男");
            user.setUserName("王凯歌");
            this.evpUserBiz.insertUserWithTx(user);
        }
        long end=System.currentTimeMillis();

        result.put("cast(ms)", (end-start));
        return result;
    }

    @GetMapping("/withoutTX")
    public JSONObject withoutTX(){
        JSONObject result=new JSONObject();

        long start=System.currentTimeMillis();
        for(int i=0;i<500;i++){
            EvpUser user=new EvpUserVo();
            user.setPhone(String.valueOf(i));
            user.setEvpAccount("wangkaige"+i);
//            user.setEvpPassword();
            user.setAddr("addr"+i);
            user.setDescription("desc"+i);
            user.setEmail("13821211755@163.com");
            user.setSex("男");
            user.setUserName("王凯歌");
            this.evpUserBiz.insertUserWithoutTx(user);
        }
        long end=System.currentTimeMillis();

        result.put("cast(ms)", (end-start));
        return result;
    }

    @GetMapping("/rabbitInsertUser")
    public JSONObject rabbitInsertUser(){
        JSONObject result=new JSONObject();

        long start=System.currentTimeMillis();
        for(int i=0;i<50;i++){
            EvpUser user=new EvpUserVo();
            Map<String,Object> headers=new HashMap<>();
            user.setPhone(String.valueOf(i));
            user.setEvpAccount("wangkaige"+i);
//            user.setEvpPassword();
            user.setAddr("addr"+i);
            user.setDescription("desc"+i);
            user.setEmail("13821211755@163.com");
            user.setSex("男");
            user.setUserName("王凯歌");
            if(i==40){

                headers.put("giveWrong", "true");
            }
            rabbitMQSender.sendUser(user,headers);
        }
        long end=System.currentTimeMillis();

        result.put("cast(ms)", (end-start));
        return result;
    }

    @GetMapping("/zentaoToken")
    public JSONObject getZentoToken(){
        String m="user";
        String f="apilogin";
        String account="admin";
        String code="devops";
        String time=String.valueOf(System.currentTimeMillis());
        String key="14cfcaa3dad91a9f5244e85ad926bfe3";
        String token;

        token = generatorZentaoToken(code, key, time);

//        StringBuilder builder=new StringBuilder("http://192.168.239.129/zentao/api.php?");
//        builder.append("m=user")
//            .append("&f=apilogin")
//            .append("&account=").append(account)
//            .append("&code=").append(code)
//            .append("&time=").append(time)
//            .append("&token=").append(token);
//        String url=builder.toString();
//
//        String toString = HttpClientUtil.getToString(url, new HashMap<>());
//        String s = new String(toString.getBytes(getStandarCharsetsOf(toString)), StandardCharsets.UTF_8);
//        System.out.println(s);

        JSONObject result=new JSONObject();
        result.put("token", token);
        return result;
    }

    private String generatorZentaoToken(String code, String key, String time) {
        MessageDigest md5= null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //加密后的字符串
        String newstr= null;
        String s = code + key + time;
        String s2 = StringInMd5(s);

        return s2;
    }

    /**
     * 16进制字符
     */
    static String[] chars = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

    public String StringInMd5(String str) {

        // 消息签名（摘要）
        MessageDigest md5 = null;
        try {
            // 参数代表的是算法名称
            md5 = MessageDigest.getInstance("md5");
            byte[] result = md5.digest(str.getBytes());

            StringBuilder sb = new StringBuilder(32);
            // 将结果转为16进制字符  0~9 A~F
            for (int i = 0; i < result.length; i++) {
                // 一个字节对应两个字符
                byte x = result[i];
                // 取得高位
                int h = 0x0f & (x >>> 4);
                // 取得低位
                int l = 0x0f & x;
                sb.append(chars[h]).append(chars[l]);
            }
            return sb.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
